package com.itheima.reggie.listener;

import com.itheima.reggie.common.LoginSessionUtil;
import com.itheima.reggie.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Configuration
@WebListener
public class SessionListener implements HttpSessionListener {
/*
    //初始化登录池<用户ID,用户session>
    private static final Map<Long,HttpSession> sessionMap = new HashMap<>();
    static{
        log.info("初始化SessionListener");
    }
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        HttpSession session=se.getSession();
        Employee loginUser=(Employee) session.getAttribute("loginUser");
        log.info("当前session对象"+session);
        if(loginUser != null){
            //已登录
            //判断是否有异地登录 如果登录 则剔除
            if(sessionMap.containsKey(loginUser.getId())){
                //如果已存在 剔除session中的登录对象
                HttpSession httpSession=sessionMap.get(loginUser.getId());
                httpSession.removeAttribute("loginUser");
            }
            sessionMap.put(loginUser.getId(),session);
        }

    }
*/


    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        //判断该session 是否登录 已登录 则 剔除session
        HttpSession session=se.getSession();
        System.out.println("当前销毁session对象"+session);
        Employee loginUser=(Employee) session.getAttribute("loginUser");
        if (loginUser != null){
            //退出登录时 剔除正在登录的集合
            LoginSessionUtil.sessionMap.remove(loginUser.getId());
        }
    }
}
